<?php


namespace App\Models\CacheModel\privatearea;


use App\Models\Api\BaseCache;
use think\Log;
use AstroTool\Cache\CacheManage;

class PrivateAreaOrders extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.private_area_orders';

    protected $cacheModel = 'privatearea.order';

    public function updateData(string $orderId, array $updateData)
    {
        try
        {
            $this->where(['order_id' => $orderId])->update($updateData);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $orderId)->rmCache();
        }
        catch (\Exception $e)
        {
            Log::write('私域H5 订单状态更新 PrivateAreaOrders model 异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
        return true;
    }

    /**
     * 订单写入
     * @param $data
     * @return int
     */
    public function insertDataGetId($data)
    {
        try
        {
            $oid = $this->insertGetId($data);
            if ($data['good_type'] === 7)
            {
                $this->listDataAdd($data['uid'], [$data['order_id'] => $oid], 2);
            } else
            {
                $this->listDataAdd($data['uid'], [$data['order_id'] => $oid], 1);
            }
        }
        catch (\Exception $e)
        {
            Log::write('私域H5 订单写入 PrivateAreaOrders model 异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return 0;
        }
        return (int)$oid;
    }

    /**
     * 私域H5
     * 获取订单列表
     * @param int $uid
     * @param int $page
     * @return array|mixed
     */
    public function getOrderList(int $uid, int $page)
    {
        $pageData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize(10)
            ->setSort('desc')
            ->setListKeyType(1)// 类型 用于分页 例如 0全部 1待支付 已支付 //
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid, 'good_type' => ['in', [1, 2, 3, 4, 5, 6]]])->column('*', 'order_id');
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = [];
                }
                return $data;
            }, 'id', [], 0);

        $goodModel = new PrivateAreaGoods();
        $questionInfoModel = new PrivateAreaQuestionInfo();
        $data = [];
        //1=>待支付 2=>支付完成 3=>未支付取消订单 4=>占星师已接单 5=>已回复待审核 6=>回复审核未通过 7=>回复结果审核通过 8=>完成 9=>用户联系客服取消（退全款或部分）
        $statusConfig = [
            1 => 1,
            2 => 2,
            3 => 0,
            4 => 3,
            5 => 3,
            6 => 3,
            7 => 4,
            8 => 5,
            9 => 6,
        ];
        foreach ($pageData['data'] as $datum)
        {
            $questionInfo = $questionInfoModel->getPrivateAreaQuestionInfo($datum['qid'], ['hash', 'status', 'create_time']);

            $goodInfo = $goodModel->getPrivateAreaGoodInfo($questionInfo['hash'], ['name', 'img']);

            $data[] = [
                'good_name' => $goodInfo['name'],
                'good_img' => $goodInfo['img'],
                'status' => $statusConfig[$questionInfo['status']],
                'order_id' => $datum['order_id'],
                'create_time' => date('Y-m-d H:i:s', $questionInfo['create_time']),
                'total_amount' => $datum['total_amount'],
                'trade_type' => (int)$datum['trade_type'],
            ];
        }
        $pageData['data'] = $data;

        return $pageData;
    }

    /**
     * 私域H5实物销售
     * 获取订单列表
     * @param int $uid
     * @param int $page
     * @return array|mixed
     */
    public function getOrderList2(int $uid, int $page)
    {
        $pageData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $uid)
            ->setPage($page)
            ->setPageSize(10)
            ->setSort('desc')
            ->setListKeyType(2)// 类型 用于分页 例如 0全部 1待支付 已支付 //
            ->getListPage(function ($ids = [], $isCache = true, $sortType = 'desc') use ($uid)
            {
                try
                {
                    $data = $this->where(['uid' => $uid, 'good_type' => 7])->column('*', 'order_id');
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = [];
                }
                return $data;
            }, 'id', [], 0);

        $data = [];
        $privateAreaMallGoodsModel = new PrivateAreaMallGoods();
        $privateAreaMallGoodsAttrModel = new PrivateAreaMallGoodsAttr();
        $nowTime = time();
        foreach ($pageData['data'] as $datum)
        {
            $extend = $datum['extend'] ? json_decode($datum['extend'], true) : [];
            if ($datum['status'] == 6 && $nowTime - $extend['kd']['send_time'] > 864000)
            {   // 已发货 等待收货 发货后 10天自动完成订单
                $orderInfo['status'] = 4;
                $orderInfo['success_time'] = $extend['kd']['send_time'] + 864000;
                $this->updateOrderInfo($datum['order_id'], ['status' => 4, 'success_time' => $orderInfo['success_time']]);
            }
            $isCheck = $extend['mall']['is_check'] ?? 0;
            $goodAttrData = $privateAreaMallGoodsAttrModel->getInfoById($datum['qid']);
            $goodInfo = $privateAreaMallGoodsModel->getInfoById($goodAttrData['gid']);
            // 1=>待支付 2=>待解答|待发货  3=>未支付订单关闭 4=>已完成 5=>已退款 6=>待收货
            switch ($datum['status'])
            {
                case 1:
                    $statusDesc = '待支付';
                    $priceDesc = sprintf("待付款：%s元", (float)$datum['total_amount']);
                    break;
                case 2:
                    $statusDesc = '待发货';
                    $priceDesc = sprintf("实付：%s元", (float)$datum['total_amount']);
                    break;
                case 3:
                    $statusDesc = '已取消';
                    $priceDesc = '';
                    break;
                case 4:
                    $statusDesc = '已完成';
                    $priceDesc = sprintf("实付：%s元", (float)$datum['total_amount']);
                    break;
                case 5:
                    $statusDesc = '已退款';
                    $priceDesc = '';
                    break;
                case 6:
                    $statusDesc = '待收货';
                    $priceDesc = sprintf("实付：%s元", (float)$datum['total_amount']);
                    break;
            }

            $statusDescTip = $this->getStatusTip($datum);
            $data[] = [
                'order_id' => $datum['order_id'],
                'img' => $goodAttrData['img'] ?? '',
                'title' => $goodInfo['name'],
                'spe_name' => $goodAttrData['name'],
                'tip' => $isCheck === 1 ? '走三方质检' : '',
                'status' => (int)$datum['status'],
                'status_desc' => $statusDescTip['des'],
                'price_desc' => $priceDesc ?? '',
                'status_tip' => $statusDescTip['tip'],
                'btn_data' => $this->getListStatusBtn($datum['status'], $datum['kd_status'], $extend['kd']['id'] ?? ''),
            ];
        }
        $pageData['data'] = $data;

        return $pageData;
    }

    /**
     * 获取订单列表不同状态订单的按钮
     * @param $status
     * @param $kdStatus
     * @param string $kdId 快递单号
     * @return array
     */
    public function getListStatusBtn($status, $kdStatus, $kdId = '')
    {
        //status 1=>待支付 2=>待解答|待发货  3=>未支付订单关闭 4=>已完成 5=>已退款 6=>待收货
        //kd_status 1=>待下单 2=>待快递员取货 3=>取消发货  50=>已揽件  30=>运输中 44=>派送中 80=>派送成功  70=>派送失败'
        $btn = [];
        switch ($status)
        {
            case 1:
                $btn[] = [
                    'name' => '立即支付',
                    'type' => 3, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                ];
                break;
            case 2:
                if ($kdStatus > 0 && $kdId)
                {
                    $btn[] = [
                        'name' => '查看物流',
                        'type' => 2, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                    ];
                }
                break;
            case 3:
                $btn[] = [
                    'name' => '查看详情',
                    'type' => 4, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                ];
                break;
            case 4:
                $btn[] = [
                    'name' => '查看物流',
                    'type' => 2, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                ];
                break;
            case 5:
                $btn[] = [
                    'name' => '查看详情',
                    'type' => 4, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                ];
                if ($kdStatus > 1 && $kdId)
                {
                    $btn[] = [
                        'name' => '查看物流',
                        'type' => 2, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                    ];
                }
                break;
            case 6:
                $btn[] = [
                    'name' => '查看物流',
                    'type' => 2, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                ];
                $btn[] = [
                    'name' => '确认收货',
                    'type' => 1, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                ];
                break;
            default:
                break;
        }
        return $btn;
    }

    /**
     * 获取订单详情不同状态订单的按钮
     * @param $status
     * @param $kdStatus
     * @param string $kdId 快递单号
     * @return array
     */
    public function getReadStatusBtn($status, $kdStatus, $kdId = '')
    {
        //status 1=>待支付 2=>待解答|待发货  3=>未支付订单关闭 4=>已完成 5=>已退款 6=>待收货
        //kd_status 1=>待下单 2=>待快递员取货 3=>取消发货  50=>已揽件  30=>运输中 44=>派送中 80=>派送成功  70=>派送失败'
        $btn = [];
        switch ($status)
        {
            case 1:
                $btn[] = [
                    'name' => '立即支付',
                    'type' => 3, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                ];
                break;
            case 5:
            case 2:
                if ($kdStatus > 0 && $kdId)
                {
                    $btn[] = [
                        'name' => '查看物流',
                        'type' => 2, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                    ];
                }
                break;
            case 4:
                $btn[] = [
                    'name' => '查看物流',
                    'type' => 2, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                ];
                break;
            case 6:
                $btn[] = [
                    'name' => '查看物流',
                    'type' => 2, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                ];
                $btn[] = [
                    'name' => '确认收货',
                    'type' => 1, //1=>确认收货 2=>查看物流 3=>立即支付 4=>查看详情
                ];
                break;
            default:
                break;
        }
        return $btn;
    }

    /**
     * 获取订单不同状态的文案和提示语
     * @param $order
     * @return string[]
     */
    public function getStatusTip($order)
    {
        $status = (int)$order['status'];
        $kdStatus = (int)$order['kd_status'];
        //status 1=>待支付 2=>待解答|待发货  3=>未支付订单关闭 4=>已完成 5=>已退款 6=>待收货
        //kd_status 1=>待下单 2=>待快递员取货 3=>取消发货  50=>已揽件  30=>运输中 44=>派送中 80=>派送成功  70=>派送失败'
        $des = '';
        $tip = '';
        switch ($status)
        {
            case 1:
                $des = '待支付';
                $tip = '商品未支付';
                break;
            case 2:
                $des = '商品准备中';
                $tip = '正在努力备货中...';
                if ($kdStatus === 2)
                {
                    $des = '待发货';
                    $tip = '等待快递揽件中...';
                }
                break;
            case 3:
                $des = '已取消';
                $tip = '商品订单已取消';
                break;
            case 4:
                $des = '已完成';
                $tip = '订单已完成';
                break;
            case 5:
                $des = '退款成功';
                $tip = '退款金额 ' . $order['return_amount'] . '元';
                break;
            case 6:
                $des = '运输中';
                $tip = $order['extend']['kd']['notify_remark'] ?? '';
                if ($kdStatus === 44)
                {
                    $des = '派件中';
                } elseif ($kdStatus === 70)
                {
                    $des = '派送失败';
                } elseif ($kdStatus === 80)
                {
                    $des = '已签收';
                }
                break;
            default:
                break;
        }
        return [
            'des' => $des,
            'tip' => $tip,
        ];
    }


    public function updateOrderInfo(string $orderId, array $updateData)
    {
        try
        {
            $this->where(['order_id' => $orderId])->update($updateData);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $orderId)->rmCache();
        }
        catch (\Exception $e)
        {
            Log::write('私域H5 订单状态更新 PrivateAreaOrders model 异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
        return true;
    }


    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        foreach ($resData as $orderId => $orderItemData)
        {
            $resData[$orderId] = arrayKeyData2int($orderItemData, ['id', 'status', 'good_type', 'uid', 'qid', 'trade_type', 'create_time', 'pay_time', 'return_time', 'channel', 'inventory_status', 'kd_status', 'return_type', 'shipping_type', 'delay_delivery_time', 'success_time']);
        }

        return $resData;
    }


    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            if ($ids)
            {
                $where = ['order_id' => ['in', $ids]];
            } else
            {
                $where = ['uid' => $type[0]];
            }
            $data = $this
                ->where($where)
                ->column('*', 'order_id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }
}
